/**
 * 日期范围选择，带至今选项
 */
import React from 'react';
import { Checkbox, DatePicker } from 'antd';

const RangePicker = React.forwardRef((props, ref) => {
    const { value = [], onChange } = props;
    const [lastEndDate, setLastEndDate] = React.useState(null);

    const handleCheck = e => {
        if (!onChange) return;
        if (e.target.checked) {
            if (value?.[0]) {
                onChange([value?.[0]]);
            }
        } else if (value?.[0] && lastEndDate) {
            onChange([value?.[0], lastEndDate]);
        }
    };

    const handleRangeChange = dates => {
        if (onChange) onChange(dates);
    };

    React.useEffect(() => {
        if (value?.[1]) {
            setLastEndDate(value?.[1]);
        }
    }, [value]);

    return (
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }} ref={ref}>
            <DatePicker.RangePicker
                value={value}
                style={{ flex: 1 }}
                onChange={handleRangeChange}
                placeholder={[
                    '开始日期',
                    value?.[0] && (value?.[1] === undefined || value?.[1] === null) ? '至今' : '结束日期'
                ]}
            />
            <Checkbox
                checked={value?.[0] && (value?.[1] === undefined || value?.[1] === null)}
                style={{ marginLeft: 24 }}
                onChange={handleCheck}
            >
                至今
            </Checkbox>
        </div>
    );
});

export default RangePicker;
